package com.example.passport.service;

import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.interceptor.UserContext;
import com.example.passport.dto.*;
import com.example.passport.entity.Logging;
import com.example.passport.entity.User;
import com.example.passport.mapper.LoggingMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LoggingService {
    @Resource
    LoggingMapper loggingMapper;
    @Resource
    UserService userService;

    /**
     * 新增用户
     */
    public void createLogging(Logging logging) {
        logging.setTenantId(logging.getTenantId());
        loggingMapper.create(logging);
    }

    /**
     * 列出用户
     */
    public ListDto<Logging> listUser(Logging condition, Pagination pagination) {
        long total = loggingMapper.count(condition);
        if (total <= 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }
        pagination.setTotal(total);
        condition.setTenantId(UserContext.getUser().getTenantId());
        List<Logging> loggingList = loggingMapper.findAll(condition, pagination);
        List<LoggingDto> loggingDtoList = loggingList.stream().map(logging -> {
            LoggingDto loggingDto=new LoggingDto();
            BeanUtils.copyProperties(logging,loggingDto);
            User user=userService.findUserByIdAndDel(loggingDto.getUserId());
            if(null==user){
                loggingDto.setUserName("");
                loggingDto.setMobile("");
            }else {
                loggingDto.setUserName(user.getName());
                loggingDto.setMobile(user.getMobile());
            }
            return loggingDto;
        }).collect(Collectors.toList());
        return new ListDto(loggingDtoList, pagination);
    }


    /**
     *修改数据
     */
    public void update(@Valid  Logging logging) {
        Long tenantId=UserContext.getUser().getTenantId();
        logging.setTenantId(tenantId);
        Logging logging1=loggingMapper.findAllByUserId(logging).get(0);
        logging1.setTenantId(tenantId);
        loggingMapper.update(tenantId,logging1.getId());
    }


    /**
     *删除数据
     */

    public void delete(long id) {
        if (loggingMapper.deleteById(UserContext.getUser().getTenantId(),id) != 1) {
            throw new BusinessException("操作失败");
        }
    }
}
